<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-23 15:16:35
 * @LastEditTime: 2019-11-08 18:08:06
 * @LastEditors: Please set LastEditors
 -->
<template>
  <div class="container">
    <div class="container_card">
      <div class="container_head">
        <svg-icon icon-class="list" />游戏列表
      </div>
      <div class="container_body">
        <div class="btn_add">
          <el-button type="primary" @click="add_games">添加游戏</el-button>
        </div>
        <template>
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="name" label="游戏名称" />
            <!-- <el-table-column
              prop="alias"
              label="游戏简称"
            />-->
            <el-table-column prop="game_id" sortable label="游戏id" />
            <!-- <el-table-column
              prop="unity_enc"
              sortable
              label="unity加密"
            >
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.unity_enc === '0' ? 'primary' : 'success'"
                  disable-transitions
                >
                  <div v-if="scope.row.state == 1">
                    开启
                  </div>
                  <div v-else>
                    禁用
                  </div>
                </el-tag>
              </template>
            </el-table-column>-->
            <!-- <el-table-column
              prop="label"
              label="游戏图标"
            >
              <template slot-scope="scope">
                <img :src="url + scope.row.icon" width="50">
              </template>
            </el-table-column>-->
            <!-- <el-table-column
              prop="state"
              label="状态"
              width="100"
              filter-placement="bottom-end"
            >
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.state === '0' ? 'primary' : 'success'"
                  disable-transitions
                >
                  <div v-if="scope.row.state == 1">
                    开启
                  </div>
                  <div v-else>
                    禁用
                  </div>
                </el-tag>
              </template>
            </el-table-column>-->
            <el-table-column fixed="right" label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="addVersion(scope.row.id)">添加版本</el-button>
                <el-button type="text" size="small" @click="addChannel(scope.row.id)">渠道设置</el-button>
                <el-button type="text" size="small" @click="save_game(scope.row.id)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <template>
          <el-dialog title="渠道列表" :visible.sync="outerVisible">
            <div>
              <el-button type="primary" plain @click="addChannelId()">添加渠道</el-button>
            </div>
            <div>
              <template>
                <el-table
                  v-loading="gameHasChannelLoading"
                  :data="gameHasChannelData"
                  style="width: 100%"
                >
                  <el-table-column label="渠道ID" prop="channel_id" />
                  <el-table-column label="渠道名称" prop="name" />
                  <!-- <el-table-column label="上传角标" prop="label">
                    <template slot-scope="scope">
                      <div @click="upload_label(scope.row.id)">
                        <div v-if="!scope.row.label">
                          <el-button size="mini" type="primary" plain>
                            <i class="el-icon-upload2" />
                          </el-button>
                        </div>
                        <div>
                          <img :src="url+scope.row.label" alt width="30">
                        </div>
                      </div>
                    </template>
                  </el-table-column> -->
                  <!-- <el-table-column label="渠道版本" prop="channel_version">
                    <template slot-scope="scope">
                      <div v-if="scope.row.channel_version">{{ scope.row.channel_version }}</div>
                      <div v-else>
                        <i class="el-icon-warning" />
                      </div>
                    </template>
                  </el-table-column> -->
                  <el-table-column label="操作" prop="desc">
                    <template slot-scope="scope">
                      <!-- <el-button type="text" size="small" @click="viewChannel(scope.row.id)">查看</el-button> -->
                      <el-button type="text" size="small" @click="addParams(scope.row)">参数配置</el-button>
                      <el-button type="text" size="small" @click="deleteChannel(scope)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </div>
            <el-dialog
              title="添加渠道"
              :visible.sync="innerVisible"
              width="70%"
              custom-class="add_channel_dialog"
              top="5vh"
              append-to-body
            >
              <div class="add_channel_div">
                <template>
                  <el-tabs
                    v-model="activeName"
                    :tab-position="tabPosition"
                    type="border-card"
                    @tab-click="handleClick"
                  >
                    <el-tab-pane width="200px" label="安卓" name="first">
                      <el-checkbox-group v-model="ruleForm">
                        <el-checkbox v-for="item in channelData" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
                      </el-checkbox-group>
                      <!-- <el-form
                        ref="ruleForm"
                        :model="ruleForm"
                        status-icon
                        label-width="100px"
                        :rules="rules"
                        class="demo-ruleForm"
                      > -->
                      <!-- <el-form-item label="选择渠道" prop="cid">
                          <el-select v-model="ruleForm.cid" filterable prop="cid" placeholder="请选择">
                            <el-option
                              v-for="item in channelData"
                              :key="item.id"
                              :label="item.name"
                              :value="item.id"
                            />
                          </el-select>
                        </el-form-item> -->
                      <!-- </el-form> -->
                    </el-tab-pane>
                    <el-tab-pane label="iOS" name="second">ios</el-tab-pane>
                    <!-- <el-tab-pane label="角色管理" name="third">角色管理</el-tab-pane>
                    <el-tab-pane label="定时任务补偿" name="fourth">定时任务补偿</el-tab-pane>-->
                  </el-tabs>

                </template>
              </div>
              <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitChannel()">提交</el-button>
                <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
              </span>
            </el-dialog>
            <div slot="footer" class="dialog-footer">
              <!-- <el-button @click="outerVisible = false">取 消</el-button> -->
              <el-button type="primary" @click="outerVisible = false">确定</el-button>
            </div>
          </el-dialog>
        </template>
        <template>
          <el-dialog title="配置参数" :visible.sync="paramsVisible" append-to-body>
            <el-form
              ref="paramsForm"
              :model="paramsForm"
              status-icon
              label-width="200px"
              class="demo-ruleForm"
            >
              <!-- <el-form-item
                label="编译类型"
              >
                <template>
                  <div>
                    <el-checkbox-group v-model="complilation" size="small" @change="comChange">
                      <el-checkbox value="0" label="编译参数" border />
                      <el-checkbox value="1" label="gameSettings" border />
                    </el-checkbox-group>
                  </div>
                </template>
              </el-form-item>-->
              <div class="params_value">
                <el-divider content-position="left">基本参数</el-divider>
              </div>
              <el-form-item label="默认签名" prop="signature_id">
                <el-select v-model="signature_id" placeholder="请选择签名">
                  <el-option
                    v-for="item in signOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <div v-for="item in paramsData" :key="item.id" :label="item.key" prop="key">
                <div class="params_value">
                  <el-divider content-position="left">{{ item.name }}</el-divider>
                </div>
                <div>
                  <el-form-item v-for="items in item.params" :key="items.id" style="margin-top:20px" :label="items.key" prop="key">
                    <el-input v-model="items.value" />
                    <span class="placeholder_params">{{ items.desc }}</span>
                  </el-form-item>
                </div>
              </div>
              <!-- <el-form-item style="margin-top:20px">
                <el-button type="primary" @click="submitParams()">提交</el-button>
              </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="paramsVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitParams()">提交</el-button>
            </div>
          </el-dialog>
        </template>
        <template>
          <el-dialog title="上传角标" :visible.sync="uploadVisible" append-to-body>
            <el-upload
              class="upload-demo"
              drag
              :data="upload_data"
              :headers="headers"
              :action="upload_url"
              :on-change="handleBefore"
              :on-exceed="handleExeed"
              :on-success="handleSuccess"
              multiple
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-dialog>
        </template>
      </div>
      <!-- 添加游戏版本 -->
      <el-dialog title="添加游戏版本" :visible.sync="versionVisible">
        <el-form ref="versionForm" :model="versionForm" label-width="100px" class="demo-ruleForm">
          <el-form-item>
            <el-tag
              v-for="tag in versionData"
              :key="tag.id"
              closable
              @close="handleClose(tag)"
            >{{ tag.version }}</el-tag>
          </el-form-item>
          <el-form-item label="版本号" prop="version">
            <el-input v-model="versionForm.version" />
          </el-form-item>
          <el-form-item label="上传母包" prop="icon">
            <el-upload
              class="upload-demo"
              :action="upload_apk"
              :headers="headers"
              :data="versionForm"
              :on-remove="handleRemove"
              :on-success="handleApkSuccess"
              :file-list="apk_list"
              :limit="uploadLimit"
              :on-change="handleApkBefore"
              :on-exceed="handleExeed"
            >
              <el-button size="small" type="primary">点击上传文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传apk文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitVersionForm('versionForm')">创建</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import config from '../../config/config'
export default {
  data() {
    // const typeValidator = (rule, value, callback) => {
    //   if (!this.form.type) {
    //     callback(new Error('请选择一种类型'))
    //   }
    //   callback()
    // }
    // const cidValidator = (rule, value, callback) => {
    //   if (value === undefined) {
    //     callback(new Error('请选择一个渠道'))
    //   }
    //   callback()
    // }
    return {
      tableData: [],
      url: config.BASE_IMG,
      complilation: [],
      upload_data: {},
      signature_id: '',
      activeName: 'first',
      tabPosition: 'left',
      outerVisible: false,
      innerVisible: false,
      versionVisible: false,
      versionCompile: false,
      versionGameSettings: false,
      ruleForm: [],
      channelId: '0',
      apk_list: [],
      signOptions: [],
      uploadLimit: 1,
      upload_apk: config.BASE_URL + 'upload_apk',
      channel_version: '',
      channelData: [],
      paramsTable: [],
      versionForm: {},
      id: 0,
      gc_id: 0,
      type: [],
      form: {},
      versionData: [],
      restaurants: [],
      game_id: 0,
      dialogState: false,
      dialogTable: false,
      gameHasChannelData: [],
      gameHasChannelLoading: true,
      paramsVisible: false,
      paramsData: [],
      channel_id: 0,
      dialogFormVisible: false,
      uploadVisible: false,
      // rules: {
      //   alias: [{ required: true, message: '请输入别名', trigger: 'blur' }],
      //   cid: [{ required: true, validator: cidValidator }]
      // },
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('_token')
      },
      upload_url: config.BASE_URL + 'channel/upload_save',
      paramsForm: {
        'data': []
      }
    }
  },
  mounted() {
    // this.$api.getChannel([]).then(res => {
    //   this.channelData = res.data
    // })
    this.$api.get_game_list([]).then(res => {
      console.log(res)
      this.tableData = res.data
    }).catch(() => {
      this.$notify.error({
        title: '错误',
        message: '网络错误！'
      })
    })
    this.$api.get_sign_list([]).then(res => {
      this.signOptions = res.data
    })
  },
  methods: {
    handleApkBefore() {
      this.headers = {
        'Authorization': 'Bearer ' + localStorage.getItem('_token')
      }
      if (!this.versionForm.version) {
        this.$notify.error({
          title: '错误',
          message: '请先填写版本号！'
        })
        return false
      }
    },
    handleRemove(e) {

    },
    handleApkSuccess(e) {
      console.log(e)
    },
    addChannelId() {
      this.innerVisible = true
      this.ruleForm = []
      this.$api.get_exe_channel({ game_id: this.game_id }).then(res => {
        console.log(res)
        this.channelData = res.data
      })
    },
    submitVersionForm() {
      this.$api.add_game_version(this.versionForm).then(res => {
        console.log(res)
        this.apk_list = []
        this.versionData = res.data
        this.versionForm.version = ''
      })
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      const results = []
      console.log(restaurants)
      restaurants.map(function(item) {
        if (item.value.indexOf(queryString) > -1) {
          results.push(item)
        }
      })
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    handleSelect(e) {
      console.log(e)
    },
    loadAll(id) {
      console.log(id)
      // const data = {
      //   cid: id,
      //   gid: this.game_id
      // }
      // this.$api.get_channel_version(data).then(res => {
      //   this.restaurants = res.data
      // })
    },
    handleClose(e) {
      const i = this.versionData.indexOf(e)
      const data = {
        id: e.id,
        gid: this.game_id
      }
      this.$api.delete_game_version(data).then(res => {
        this.versionData.splice(i, 1)
      })
    },
    view_params(id) {
      const data = {
        cid: id,
        gid: this.game_id
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$api.view_params(data).then(res => {
        this.paramsTable = res.data
        // for (let i = 0; i < res.data.length; i++) {
        //   // this.paramsTable[i].jsons = JSON.parse(this.paramsTable[i].json)
        // }
        loading.close()
        this.dialogTable = true
      })
    },
    addVersion(id) {
      this.versionVisible = true
      const data = {
        id: id
      }
      this.versionForm.game_id = id
      this.$api.get_game_version(data).then(res => {
        console.log(res)
        this.versionData = res.data
      })
    },
    add_games() {
      this.$router.push('/games/add')
    },
    save_game(id) {
      this.$router.push({
        path: '/games/add',
        query: {
          id: id
        }
      })
    },
    comChange(e) {
      this.type = e
      console.log(e)
    },
    handleSuccess(res, fileList) {
      if (res.access_token) {
        localStorage.setItem('_token', res.access_token)
      }
      this.uploadVisible = false
      this.paramsForm.data = res.data
    },
    handleExeed(res) {
      this.$notify.error({
        title: '错误',
        message: '最多只能上传一张图片！'
      })
    },
    handleBefore(file, fileList) {
      this.headers = {
        'Authorization': 'Bearer ' + localStorage.getItem('_token')
      }
    },
    addChannel(id) {
      this.game_id = id
      this.outerVisible = true
      this.getGameChannel()
    },
    submitChannel(id) {
      const data = {
        id: this.game_id,
        cid: this.ruleForm
        // alias: this.ruleForm.alias
      }
      console.log(this.ruleForm)
      // this.$refs.ruleForm.validate(valid => {
      // if (valid) {
      this.$api.game_channel(data).then(res => {
        this.getGameChannel()
        this.innerVisible = false
      })
      // }
      // })
    },
    handleClick() {

    },
    deleteChannel(e) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          gid: this.game_id,
          cid: e.id
        }
        this.$api.detach_channel(data).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          for (let i = 0; i < this.gameHasChannelData.length; i++) {
            if (this.gameHasChannelData[i].id === e.id) {
              this.gameHasChannelData.splice(this.gameHasChannelData.indexOf(this.gameHasChannelData[i], 1))
              break
            }
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getGameChannel() {
      const data = {
        id: this.game_id
      }
      this.gameHasChannelLoading = true
      this.$api.get_game_channel(data).then(res => {
        console.log(res)
        this.gameHasChannelData = res.data
        this.gameHasChannelLoading = false
      })
    },
    resetForm() {
      this.ruleForm = []
    },
    upload_label(id) {
      this.upload_data = {
        id: id
      }
      this.uploadVisible = true
    },
    addParams(row) {
      // this.id = row.channel_id
      this.channel_id = row.channel_id
      const data = {
        channel: row,
        gid: this.game_id
      }
      const datas = {
        id: row.channel_id,
        game_id: this.game_id
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      console.log(row)
      this.channel_version = row.channel_version
      this.versionCompile = row.compile
      this.loadAll(row.id)
      this.versionGameSettings = row.gameSettings
      this.$api.get_channel(datas).then(res => {
        this.paramsForm.data = res.data
        this.signature_id = res.data.signature_id
      })
      this.$api.get_params_value(data).then(res => {
        console.log(res.data)
        loading.close()
        this.paramsVisible = true
        this.paramsData = res.data
      })
    },
    submitParams() {
      const data = {
        'data': this.paramsData,
        'signature_id': this.signature_id,
        // 'form': this.paramsForm.data,
        'type': this.type,
        'game_id': this.game_id,
        'channel_id': this.channel_id
        // 'channel_version': this.channel_version,
        // 'compile': this.versionCompile,
        // 'gameSettings': this.versionGameSettings
      }
      console.log(data)
      this.$api.save_params(data).then(res => {
        this.paramsVisible = false
        this.getGameChannel()
      })
    }
  }
}
</script>
<style>
.btn_add {
  margin-bottom: 40px;
}
.el-tag {
  margin-right: 10px;
}
.add_channel_div {
  height: 60vh;
  overflow: auto;
  /* border: 1px solid #f2f6fc; */
}
.add_channel_dialog .el-dialog__body {
  padding: 20px 0 !important;
}
.add_channel_dialog .el-tabs {
  height: 100%;
}
.el-dialog {
  position: absolute;
  top: 5%;
  left: 50%;
  margin: 0 !important;
  transform: translate(-50%, 0);
  display: flex;
  max-height: 90vh;
  max-width: calc(100% - 30px);
  flex-direction: column;
}

.el-dialog__body {
  overflow: auto;
}
.params_value{
  padding:20px 0 ;
  font-weight: bold;
  color: #303133
}
.placeholder_params{
  color: #909399;
  font-size: 10px
}
</style>
